package com.bawei.aidl_client

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import com.bawei.aidl_server.IMyAidlInterface

class MainActivity : AppCompatActivity() {
    private val serviceConnection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            //关键的地方：绑定成功，将服务端返回的binder转成IMyAidlInterface对象
            val iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service)
            //调用远程服务的方法
            val num =  iMyAidlInterface.add(3,4)
            Toast.makeText(this@MainActivity,"$num",Toast.LENGTH_SHORT).show()

        }

        override fun onServiceDisconnected(name: ComponentName?) {
            TODO("Not yet implemented")
        }

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        //1.跨进程绑定服务,配置服务端的包名和action
        val intent = Intent()
        intent.action = "com.bawei.2001a.service"
        intent.`package` = "com.bawei.aidl_server"
        bindService(intent,serviceConnection, BIND_AUTO_CREATE)
    }
    //2。解绑
    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
    }





}